//
//  Keychain.swift
//  LiveTrivia
//
//  Created by 李响 on 2019/1/9.
//  Copyright © 2019 LiveTrivia. All rights reserved.
//

import Foundation
import KeychainAccess

enum Keychain {}

extension Keychain {
    
    private struct Wrapper<T: Codable>: Codable {
        let value: T
    }
    
    static func set<T: Codable>(_ value: T?, for key: String) {
        do {
            if let value = value {
                let encoded = try JSONEncoder().encode(Wrapper(value: value))
                try shared.set(encoded, key: key)
                
            } else {
                try shared.remove(key)
            }
        } catch {
            print("Keychain set \(error)")
        }
    }
    
    static func get<T: Codable>(for key: String) -> T? {
        do {
            guard let data = try shared.getData(key) else {
                return nil
            }
            
            return try JSONDecoder().decode(Wrapper<T>.self, from: data).value
            
        } catch {
            print("Keychain get \(error)")
            return nil
        }
    }
}

extension Keychain {
    
    private static let shared = KeychainAccess.Keychain(
        service: "com.shengsheng.social"
    ).accessibility(.afterFirstUnlock)
}

extension Keychain {
    
    /// 设备UUID
    static var uuid: String {
        let key = "UUID"
        guard let cache: String = get(for: key) else {
            let new = UIDevice.current.identifierForVendor?.uuidString ?? ""
            set(new, for: key)
            return new
        }
        return cache
    }
}
